

# -*- coding: cp936 -*-
import pygame,sys,random
from random import randint
import tkMessageBox
from pygame.locals import * #引用模块

pygame.init()
width = 480
height = 480 #设置窗口大小
screen=pygame.display.set_mode((width, height))#
black, red, blue, white = (0,0,0), (255,0,0), (0,0,255), (255,255,255)
empty = 0
xxx = -1
ooo = 1
computer = xxx

def draw_game():
    pygame.draw.rect(screen, white, (0, 0, width, height))

    pygame.draw.line(screen, black, (160, 0), (160, 480), 5)
    pygame.draw.line(screen, black, (320, 0), (320, 480), 5)
    pygame.draw.line(screen, black, (0, 160), (480, 160), 5)
    pygame.draw.line(screen, black, (0, 320), (480, 320), 5)#  画井字框架

    for row, line in enumerate(state):                          #row, line => 0,[0,0,0]  1,[0,0,0]  2,[0,0,0]

        for col, val in enumerate(line):                  #col, val => 0,0  1,0  2,0

            if val == xxx:
                # Draw an X as two crossing lines. #画一个X作为两个交叉线

                
                upper_left = (col * 160 + 5, row * 160 + 5)
                lower_right = (col * 160 + 155, row * 160 + 155)
                pygame.draw.line(screen, red, upper_left, lower_right, 5)
                
                upper_right = (col * 160 + 155, row * 160 + 5)
                lower_left = (col * 160 + 5, row * 160 + 155)
                pygame.draw.line(screen, red, upper_right, lower_left, 5)
            elif val == ooo:
                rect = (col * 160 + 5, row * 160 + 5, 150, 150)
                pygame.draw.ellipse(screen, blue, rect, 5)
            else:
                assert val == empty
                continue
          
    pygame.display.flip()

def dian(player):
    if all(val == empty for line in state for val in line):
        row = random.randrange(3)
        col = random.randrange(3)
        result = (row, col)
    else:
        result = best_move(player)
##        if state[row][col] == 0:

##            state[row][col] = 1

##            break

    return result
##    draw_game()

##    pygame.display.flip()


def best_move(player):
    best = None
    for row, line in enumerate(state):
        for col, val in enumerate(line):
            if val == empty:#判断是不是空位


                state[row][col] = player

                if panduan() == player:#从这

                    state[row][col] = empty
                    return (ooo, (row, col))


                counter = best_move(player * -1)


                if best is None or best[0] <= (counter[0] * -1):
                    best = (counter[0] * -1, (row, col))


                state[row][col] = empty#到这，是模拟下在每一个空位能否胜利


    if best is None: best = (empty, None)#这步判断为平局


    return best#返回最佳步骤


def panduan():
    for val in range(3):
        # Check matching row. 检查匹配的行。


        if state[0][val] == state[1][val] == state[2][val] != empty:    #判断每一列中三个图形是否都相同 (!= empty) 可以省略

            return state[0][val]
                              
        # Check matching column. 检查匹配的列。


        if state[val][0] == state[val][1] == state[val][2] != empty:    #判断每一行中三个图形是否都相同 (!= empty) 可以省略

            return state[val][0]

        # Check matching diagonal. 检查匹配的对角。


        if state[0][0] == state[1][1] == state[2][2] != empty:          #判断 \ 中三个图形是否都相同 (!= empty) 可以省略 

            return state[1][1]

        if state[0][2] == state[1][1] == state[2][0] != empty:          #判断 / 中三个图形是否都相同 (!= empty) 可以省略 

            return state[1][1]

def show_result_o():                        #判断O和X的结果
    result_font = pygame.font.Font(None, 80)
    result = result_font.render('o' + ' Win!!', 1, (0, 0, 0))
    screen.fill([255, 255, 255])
    screen.blit(result, [(width - result.get_width()) / 2, (height - result.get_height()) / 2])
    pygame.display.flip()
def show_result_x():
    result_font = pygame.font.Font(None, 80)
    result = result_font.render('x' + ' Win!!', 1, (0, 0, 0))
    screen.fill([255, 255, 255])
    screen.blit(result, [(width - result.get_width()) / 2, (height - result.get_height()) / 2])
    pygame.display.flip()
def Quit():
    pygame.quit()
    sys.exit()

def Star_game():
    global state,turn
    state = [[empty] * 3,[empty] * 3,[empty] * 3]
    draw_game()
    turn = xxx
    pygame.display.flip()
Star_game()

while True:
    draw_game()

    pygame.display.flip()
          
    event  =  pygame.event.wait()
              
    pos = None

    temp = 0

    if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()
    elif event.type == KEYDOWN:
        if event.key == K_F1:     #点击F1重新开始
            Star_game()
            draw_game()
            pygame.display.flip()
        elif event.key == K_F2:   #点击F2是退出
            pygame.event.post(pygame.event.Event(QUIT))    
    elif event.type == MOUSEBUTTONDOWN and event.button == 1:     #鼠标能够点击左键
        pos = (event.pos[1] / 160, event.pos[0] / 160)
##        row, col = pos

##        state[row][col] = -1

##        draw_game()

##        for i in range(3):

##            for j in range(3):

##                if state[i][j] == 0:

##                    temp += 1

##        if temp >= 2:

##            dian()

    elif event.type == pygame.KEYDOWN:
        if event.key == K_s:#点击s开始
            Star_game()

    if computer != turn:
        pos = dian(turn)[1]

    if pos is None: continue
    row, col = pos
    if state[row][col] == empty:
        state[row][col] = turn
        turn *= -1
        draw_game()
        
    if panduan() == -1:
        show_result_x()
        Quit()
    elif panduan() == 1:
        show_result_o()
        Quit()



